<template>
  <Dialog
    v-model="dialogVisible"
    width="80vw"
    :title="t('order.applyDeliveryQuantity')"
    max-height="70vh"
    :before-close="() => closeDialog()"
  >
    <div>
      <!--    展示字段-->
      <Descriptions :schema="descriptionSchema" :data="orderInfo" />
      <div class="flex flex-items-center my-20px text-14px font-bold">{{
        t('order.productInfo')
      }}</div>
      <el-table
        :data="orderInfo.list"
        highlight-current-row
        stripe
        border
        ref="tableRef"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column
          :label="t('wholesalOrder.warehouse')"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(operatorOptions.warehouse, row.wid) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.code')"
          prop="code"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.name')"
          prop="name"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.type')"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(operatorOptions.is_futures, row.is_futures) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.arrivalDate')"
          prop="arrival_date"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('order.realArrivalDate')"
          prop="real_arrival_date"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('order.quantityPurchased')"
          prop="quantity"
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <!-- <el-table-column
          :label="t('order.theQuantityToBeShipped')"
          prop="pending_quantity"
          min-width="120"
          :show-overflow-tooltip="true"
        /> -->
        <el-table-column
          :label="t('order.applyDeliveryQuantity')"
          min-width="180"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            <el-input-number
              v-if="row.fl_warehouse_id"
              v-model="row.ship_quantity"
              :min="1"
              :max="row.quantity"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="t('order.originalPrice')"
          min-width="160"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.original_price }}({{ row.actual_quoted_currency_name }})
          </template>
        </el-table-column>
        <el-table-column
          :label="t('order.discountedPrice')"
          min-width="160"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.actual_price }}({{ row.actual_quoted_currency_name }})
          </template>
        </el-table-column>
        <el-table-column
          :label="t('order.theActualPricePaid')"
          min-width="160"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.actual_selling_price }}({{
              useEnumeratePicker(operatorOptions.currency, orderInfo?.currency ?? '')
            }})
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.brand')"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(operatorOptions.brand, row.brand) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.computingPower')"
          prop="hashrate"
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.warranty')"
          prop="expiration_date"
          min-width="120"
          :show-overflow-tooltip="true"
        />
      </el-table>
    </div>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog()">
        {{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit()">
        {{ t('order.confirm') }}
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="tsx">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { useEnumeratePicker } from '@/utils'
import { ElMessageBox } from 'element-plus'
import {
  partDeliveryApplyApi,
  partDeliveryApplyListApi,
  partDeliveryApplyAuditApi
} from '@/api/order'
const props = defineProps({
  orderInfo: {
    type: Object,
    default: () => {}
  },
  operatorOptions: {
    type: Object,
    default: () => {}
  }
})
const emit = defineEmits(['refresh'])
const { t } = useI18n()
const dialogVisible = ref<boolean>(false)
const selectable = (row: Record<string, any>) => [0].includes(row.is_futures)
//批量勾选
const multipleSelection = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}
const descriptionSchema = ref<any[]>([
  {
    field: 'user',
    label: t('order.customer')
  },
  {
    field: 'order_no',
    label: t('order.orderCode')
  },
  {
    field: 'total_amount',
    label: t('order.theTotalAmountOfTheOrder')
  },
  {
    field: 'order_status',
    label: t('order.orderStatus'),
    slots: {
      default: (data: any) => {
        const statusMap = {
          10: '#FFA500', // 黄色 - 待处理
          20: '#FFD700', // 黄色
          21: '#32CD32', // 绿色
          30: '#1E90FF', // 蓝色
          40: '#9370DB', // 紫色
          50: '#20B2AA', // 青色
          70: '#c8c9cc', // 红色 - 已取消
          100: '#67c23a' // 绿色 - 已完成
        }
        const color = statusMap[data.order_status] || 'var(--el-color-warning)'
        return (
          <span
            style={`color: ${color}; background-color: var(--el-color-info-light-9); font-weight: 600; font-size: 12px; padding: 5px 15px; border-radius: 4px`}
          >
            {useEnumeratePicker(props.operatorOptions.status, data.order_status)}
          </span>
        )
      }
    }
  },
  {
    field: 'pay_amount',
    label: t('order.theAmountToBePaid')
  },
  {
    field: 'pay_status',
    label: t('order.payStatus'),
    slots: {
      default: (data: Record<string, any>) => {
        return <span>{useEnumeratePicker(props.operatorOptions.pay_status, data.pay_status)}</span>
      }
    }
  },
  {
    field: 'delivery_method',
    label: t('order.receiptMethod'),
    slots: {
      default: (data: Record<string, any>) => {
        return (
          <span>
            {useEnumeratePicker(props.operatorOptions.delivery_method, data.delivery_method)}
          </span>
        )
      }
    }
  },
  {
    field: 'part_delivery_amount',
    label: t('order.maxDeliveryAmount')
  }
])
//获取数据
const tableLoading = ref(false)
const dataList = ref([])

const submit = async () => {
  if (!multipleSelection.value.length) {
    return ElMessage.warning(t('common.selectText') + t('order.productInfo'))
  }
  if (multipleSelection.value.some((item: any) => !item.ship_quantity)) {
    return ElMessage.warning(t('common.inputText') + t('order.deliveryQuantity'))
  }
  // 校验发货商品总金额不能大于部分发货金额
  const totalAmount = multipleSelection.value.reduce((sum: number, item: any) => {
    // 商品数量 * 实际付款价格
    return sum + Number(item.ship_quantity) * Number(item.actual_selling_price || 0)
  }, 0)
  if (
    props.orderInfo.part_delivery_amount &&
    totalAmount > Number(props.orderInfo.part_delivery_amount)
  ) {
    return ElMessage.warning(t('order.message.maxDeliveryAmount'))
  }

  ElMessageBox.confirm(t('common.message.operate'), t('common.tip'), {
    confirmButtonText: `${t('order.confirm')}`,
    cancelButtonText: `${t('system.parameterConfig.cancel')}`,
    type: 'warning'
  })
    .then(async () => {
      const items = multipleSelection.value.map((item: any) => {
        return {
          order_item_id: item.id,
          apply_quantity: item.ship_quantity
        }
      })
      const res = await partDeliveryApplyApi({
        order_id: props.orderInfo.id,
        items: items
      })
      console.log('res', res)
      if (res.code === 0) {
        emit('refresh')
        closeDialog()
      }
    })
    .catch(() => {
      console.log('取消')
    })
}
onMounted(() => {
  console.log('props.orderInfo', props.orderInfo)
})
const tableRef = ref()
watch(
  () => dialogVisible.value,
  async (val) => {
    if (!val) {
      // 当对话框关闭时，清空多选
      multipleSelection.value = []
    } else {
      // 默认全部选中
      await nextTick()
      tableRef.value && tableRef.value.toggleAllSelection()
    }
  }
)
const closeDialog = () => {
  dialogVisible.value = false
}
defineExpose({
  dialogVisible
})
</script>
<style lang="less" scoped></style>
